﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Web;

using DotNetOpenAuth.OpenId.RelyingParty;
using DotNetOpenAuth.OpenId.Extensions.AttributeExchange;
using DotNetOpenAuth.OpenId.Extensions.ProviderAuthenticationPolicy;
using DotNetOpenAuth.OpenId.Extensions.SimpleRegistration;

using ASPSnippets.FaceBookAPI;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using MyLib.MyBase.MyWeb;
using MyChocCuoi.Setting;
using MyLib.MyUtility;
using System.IO;
using System.Collections.Specialized;
using MyChocCuoi.DB.Member;
using DBMember = MyChocCuoi.DB.Member;
namespace MyLoad.LoadMember
{
    public class LLogin : MyLoadWeb
    {

        public LLogin(MyASHX CurrentPage)
        {
            this.CurrentPage = CurrentPage;
            Init();
        }
        // Hàm trả về chuỗi có chứa mã HTML
        protected override string BuildHTML()
        {
            try
            {
                //Nếu là logout
                if (!string.IsNullOrEmpty(CurrentPage.Request.QueryString["lid"]))
                {
                    Logout();
                    if (string.IsNullOrEmpty(CurrentPage.PreviusURL))
                    {
                        CurrentPage.Response.Redirect(MyConfig.Domain, false);
                    }
                    else
                        CurrentPage.Response.Redirect(CurrentPage.PreviusURL, false);

                    return string.Empty;
                }

                string code = CurrentPage.Request.QueryString["code"];

                if (string.IsNullOrEmpty(code))
                {
                    WebSetting.LoginReturnURL = CurrentPage.PreviusURL;
                    //Nếu đang đăng nhập rồi thì ko đăng nhập nữa
                    if(!WebSetting.MemberLogined.IsNull)
                    {
                        CurrentPage.Response.Redirect(WebSetting.LoginReturnURL, false);
                        return string.Empty;
                    }
                    FacebookLogin();
                }
                else
                {
                    GetFaceBookInfo(code);

                    if (string.IsNullOrEmpty(WebSetting.LoginReturnURL))
                        CurrentPage.Response.Redirect(MyConfig.Domain, false);
                    else
                        CurrentPage.Response.Redirect(WebSetting.LoginReturnURL, false);
                }

                return string.Empty;
            }
            catch 
            {
                return string.Empty;
            }
        }

        void Logout()
        {
            WebSetting.RemoveCookie();
            WebSetting.RemoveLogin();
        }


        private void FacebookLogin()
        {
            FaceBookConnect.API_Key = WebSetting.FacebookAppID;
            FaceBookConnect.API_Secret = WebSetting.FacebookAppSecret;
            FaceBookConnect.Authorize("user_photos,email", MyConfig.Domain + MyCurrent.CurrentPage.Request.RawUrl); //Request.Url.AbsoluteUri.Split('?')[0]);
        }

        private void GetFaceBookInfo(string code)
        {
            FaceBookConnect.API_Key = WebSetting.FacebookAppID;
            FaceBookConnect.API_Secret = WebSetting.FacebookAppSecret;

            string data = string.Empty;
            try
            {
                data = FaceBookConnect.Fetch(code, "me");
            }
            catch
            {
                return;
            }
            var mInfo = FacebookInfo.Deserialize(data);

            //Nếu đăng nhập không thành công thì chuyển đến trang thông báo
            if (mInfo.IsNull)
            {
                LoadStatic.LError.RedirectErrorLink(LoadStatic.LError.ErrorType.LoginFail);
                return;
            }

            DBMember.Member mMember = new DBMember.Member();
            MemberObject mObject = new MemberObject();
            try
            {
                mObject = mMember.Sync(mInfo);
            }
            catch (Exception ex)
            {
                mLog.Error(ex);
            }

            if (mObject.IsNull)
            {
                LoadStatic.LError.RedirectErrorLink(LoadStatic.LError.ErrorType.LoginFail);
                return;
            }

            WebSetting.MemberLogined = mObject;

            //Lưu xuống cookie
            WebSetting.SaveCookie(mObject);

        }
    }
}
